package com.shensi.adminCollect.service.station.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.exception.CustomException;
import com.shensi.adminCollect.controller.station.ApiRequestBean;
import com.shensi.adminCollect.controller.station.RSASignature;
import com.shensi.adminCollect.controller.station.StationController;
import com.shensi.adminCollect.domain.station.Enterprise;
import com.shensi.adminCollect.domain.station.PayWay;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.domain.station.dto.AutoPayWayDto;
import com.shensi.adminCollect.domain.station.dto.AutoPayWayInfo;
import com.shensi.adminCollect.domain.station.dto.RateSettingDto;
import com.shensi.adminCollect.mapper.station.EnterpriseMapper;
import com.shensi.adminCollect.mapper.station.PayWayMapper;
import com.shensi.adminCollect.mapper.station.StationMapper;
import com.shensi.adminCollect.service.station.IPayWayService;
import com.shensi.adminCollect.domain.system.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 油站信息Service业务层处理
 *
 * @author qujia
 * @date 2020-12-08
 */
@Service
public class PayWayServiceImpl implements IPayWayService {
    private static final Logger log = LoggerFactory.getLogger(PayWayServiceImpl.class);
    @Autowired
    private PayWayMapper payWayMapper;

    @Autowired
    private StationController stationController;
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private StationMapper stationMapper;

    private String tianqueURLVal = "https://openapi.tianquetech.com";


    private String tradeReversePayPrivatekey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCjpAs/ZC8J+rL0vAFXvXmRCjga4pzLP5t/8TbmR3CeS3heYtw9ahE4gwkkqdwE9J7FoIUTkd9M/2v3k6aO4zQjtPj42zw6yX0XaJJpTF2MTagKZ8g1Sk9tLOE+tDjbfb6KFXe424ia6YcRC6gPdtfYMp508PH7+2HyYJneNjouJruQePibiQQ4gCrP6/hvyzQHDXO4h5kUbNIC0gcf0OgDqX2VpcRZv0mp/eu/2aC6O1qbJUkIJKPOzRMzapUEYAmuKN+XrGiTRkFBWF2LGWTesKWqeqV1IgbnMxXV6IvgZbVMTZ12OR1TuCcyf1MI84ONQ1/7JVUBGbJciEqRVlmXAgMBAAECggEAWXHbLAUoqP29P4Rb/4dzoVHCpP9k0Lut1VsVtP0rk3qRCpZi57bIPulw3/dwac0D0+YPl0jOk5mxfBvamJOb9kB/Lhc3brKfi2H/VUsGfyAbT8S2bFp326cCX3HG+kJbGcLuM77bhkFLMIf8jqdZB7VzY1woCKG5QfCHaiyd1Ic7Qj2dwiVFwNkFrZGcwCnvgZdlt2UyPoKWIyOEicU4XDCTwGLcBlRKmSQrvn95q0hV8+p8dwJxOrmXYi39JVjDQLkfk/+EfHvlHoxuMGwHvpaVPMHzzLfwssBG8ZMIiYcPOaIEU8UdXtwYarRa56YIEyuM5dQ0kaF4tsQtTt8/EQKBgQDXyFoeeeJ0raLGncFYFuZHSY/osDLhA8mWsxRZ3O9FtvXfmFiKGOfBIb5R0DgksJ3bnt3cPeH8HtHb9W//zDTJAaiKEp6CYlZqjfZfbiZvdNFkADN3RvwblByT6WinveufjDB0NJ7GUkjcsa0fJe6iHnyHrzLfL/JYXL6Q5BR4gwKBgQDCI9iWlb6S0I0pYGFoopkIKEfK34v6V94SJmE36Et1Jw/OhW/mMDPm05SuOijWRwggYQbGhkM5nAlvurBWDLDNF0Q69J3liJ78kt6iu4byMXhSAbL82cdu3xRv7h1l5VW0RJmjY/s1fSwP+33R+v7vzYNA2oZug7br0+5X2UaGXQKBgAU40gV+yZ4tPY008CLjmvsKqrLk4LZVUyGUf9+U2y2CufyJQUtGQwWHfYWZVmJ867UO6SuVS8zAKi/6hpVYKcbbhWqh/LgHDTRS7y1sCv4Tg6W544T1cNByCycBNQkqLXOU/u8w/s6p2x2MJzZjwpylxDm8YazJCkJdLDdxbZVlAoGAO2x1c0JKnu2vB6c0qa57YP/TWcmrMumKU8vjnhVAY4+dSv2VDsRaXqEMtXef4FbFqgOI62NVWGDmkoh2SSCBTYV9oP4XBpcW8wCRnQYBfEigJ5nVi4etf8ZQnyInZXUZEqCc1mJYFjtGLW4xSQCm4Afr0QISe+ldKDoqjkE3URECgYBZchQGPb8PY/GMnYp9uM+osyhX8y02dXjRMFc01JwxUGWhp/WzRsDfjv2YSLm/ZfWkV3piLhEXPU6U8zp8Kp7butH1e8atjs9Vw2LqDYMHWFfBpIvLg1zvRNvS5smpkBIlhxupWUumLfgaSNGbYCbLpZ6z8qNgOrK3LV9kfHuBzg==\n";


    @Override
    public int setShowPayWayIds(Station station) {

        return  stationMapper.setShowPayWayIds(station);
    }

    /**
     * 查询支付方式信息
     *
     * @param payWayId 支付方式信息
     * @return 油罐信息
     */
    public PayWay selectPayWayById(Long payWayId) {
        return payWayMapper.selectPayWayById(payWayId);
    }

    @Override
    public List<PayWay> selectPayWayByIds(Long[] payWayIds) {
        return payWayMapper.selectPayWayByIds(payWayIds);
    }

    /**
     * 查询支付方式信息列表
     *
     * @param payWay 支付方式信息
     * @return 支付方式信息集合
     */
    public List<PayWay> selectPayWayList(PayWay payWay) {
        return payWayMapper.selectPayWayList(payWay);
    }

    /**
     * 新增支付方式信息
     *
     * @param payWay 支付方式信息
     * @return 结果
     */
    public int insertPayWay(PayWay payWay) {
        Date updateTime = new Date();
        payWay.setUpdateTime(updateTime);
        return payWayMapper.insertPayWay(payWay);
    }

    /**
     * 修改支付方式信息
     *
     * @param payWay 支付方式信息
     * @return 结果
     */
    @CacheEvict(value = {"EnterpriseServiceImpl_selectStaPayWay"},
            key = "'**'",
            condition = "#root.args[0] != null"
    )
    public int updatePayWay(PayWay payWay) {

        Date updateTime = new Date();
        payWay.setUpdateTime(updateTime);
        int flag=0;
        flag = payWayMapper.updatePayWay(payWay);
        return flag;
    }

    public  String updateSxfPayWay(PayWay payWay ) {
        try {




//            PayWay payWayDto = new PayWay();
//
//            payWayDto.setPayType("1");
//            payWayDto.setAppType("1");
//            payWayDto.setMno(payWay.getMno());
//            PayWay payWayVo  =  payWayMapper.selectPayWayListSingle(payWayDto);
//            Map<String, Object> objectMap1 = new HashMap<>();
//            Map<String, Object> objectMap2 = new HashMap<>();
//            Map<String, Object> objectMap3 = new HashMap<>();
//            Map<String, Object> objectMap4 = new HashMap<>();
//            if (payWayVo!=null){
//                BigDecimal result  = payWayVo.getServiceCharge().divide(new BigDecimal("10"));
//                objectMap1.put("rate",result);
//                objectMap3.put("rate",result);
//                if (payWay.getAppType().equals("1")){
//                    BigDecimal wxresult  = payWay.getServiceCharge().divide(new BigDecimal("10"));
//                    objectMap1.put("rate",wxresult);
//                    objectMap3.put("rate",wxresult);
//                }
//            }else{
//                objectMap1.put("rate","0.3");
//                objectMap3.put("rate","0.3");
//                if (payWay.getAppType().equals("1")){
//                    BigDecimal wxresult  = payWay.getServiceCharge().divide(new BigDecimal("10"));
//                    objectMap1.put("rate",wxresult);
//                    objectMap3.put("rate",wxresult);
//                }
//            }
//            objectMap3.put("rateType","06");
//            objectMap1.put("rateType","01");


//            PayWay payWayDtozfb = new PayWay();
//            payWayDtozfb.setPayType("1");
//            payWayDtozfb.setAppType("2");
//            payWayDtozfb.setMno(payWay.getMno());
//            PayWay payWayVoZfb  =  payWayMapper.selectPayWayListSingle(payWayDtozfb);
//            if (payWayVoZfb!=null){
//                BigDecimal result  = payWayVoZfb.getServiceCharge().divide(new BigDecimal("10"));
//                objectMap2.put("rate",result);
//                if (payWay.getAppType().equals("2")){
//                    BigDecimal zfbresult  = payWay.getServiceCharge().divide(new BigDecimal("10"));
//                    objectMap2.put("rate",zfbresult);
//                }
//            }else{
//                objectMap2.put("rate","0.3");
//                if (payWay.getAppType().equals("2")){
//                    BigDecimal zfbresult  = payWay.getServiceCharge().divide(new BigDecimal("10"));
//                    objectMap2.put("rate",zfbresult);
//                }
//            }
//            objectMap2.put("rateType","02");
//            PayWay payWayDtoyhk = new PayWay();
//            payWayDtoyhk.setPayType("1");
//            payWayDtoyhk.setAppType("3");
//            payWayDtoyhk.setMno(payWay.getMno());
//            PayWay payWayVoyhk  =  payWayMapper.selectPayWayListSingle(payWayDtoyhk);
//            if (payWayVoyhk!=null){
//                BigDecimal result  = payWayVoyhk.getServiceCharge().divide(new BigDecimal("10"));
//                objectMap4.put("rate",result);
//                if (payWay.getAppType().equals("3")){
//                    BigDecimal yhkresult  = payWay.getServiceCharge().divide(new BigDecimal("10"));
//                    objectMap4.put("rate",yhkresult);
//                }
//            }else{
//                objectMap4.put("rate","0.6");
//                if (payWay.getAppType().equals("3")){
//                    BigDecimal yhkresult  = payWay.getServiceCharge().divide(new BigDecimal("10"));
//                    objectMap4.put("rate",yhkresult);
//                }
//            }
//            objectMap4.put("rateType","07");
//
//            mapList.add(objectMap1);
//            mapList.add(objectMap2);
//            mapList.add(objectMap3);
//            mapList.add(objectMap4);


        }catch (Exception e){
            e.printStackTrace();
        }
        return "suc";
    }

    public static String getSXFPay(JSONObject reqData ) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        long timestamp = System.currentTimeMillis();
        String timestampStr = String.valueOf(timestamp);
        ApiRequestBean<JSONObject> reqBean = new ApiRequestBean<JSONObject>();
//        reqBean.setOrgId("57308998");//测试 合作机构id
//        reqBean.setOrgId("73153713");//生产合作机构id
        reqBean.setOrgId("92346959");//生产合作机构id
        reqBean.setReqId(UUID.randomUUID().toString().replaceAll("-", ""));//请求id 订单号
        reqBean.setSignType("RSA");//签名类型
        reqBean.setTimestamp(timestampStr);//请求时间
        reqBean.setVersion("1.0");//版本
        //将业务参数存放在 JSON 对象中
        reqBean.setReqData(reqData);
        String req = JSONObject.toJSONString(reqBean);
        return req;

    }

    /**
     * 删除支付信息信息
     *
     * @param payWayId 支付信息ID
     * @return 结果
     */
    public int deletePayWayById(Long payWayId) {
        return payWayMapper.deletePayWayById(payWayId);
    }

    @Override
    public List<AutoPayWayDto> autoPayWayList(AutoPayWayDto autoPayWayDto) {
        return payWayMapper.autoPayWayList(autoPayWayDto);
    }

    /**
     * 新增自动切换
     *
     * @param autoPayWayDto
     * @return 结果
     */
    @Override
    public AjaxResult insertAutoPayWay(AutoPayWayDto autoPayWayDto) {
        Enterprise enterprise = enterpriseMapper.selectEnterpriseById(autoPayWayDto.getEnterpriseId());
        autoPayWayDto.setEnterpriseName(enterprise.getEnterpriseName());

        for (AutoPayWayInfo automaticClassInfo : autoPayWayDto.getAutoPayWayInfos()) {
            if (null == automaticClassInfo.getStationId()) {

                return AjaxResult.error("油站id不能为空");
            }
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();

        queryMap.put("enterpriseId", autoPayWayDto.getEnterpriseId());


        List<Map<String, Object>> i = payWayMapper.selectAutoPayWay(queryMap);
        if (i.size() > 0) {
            return AjaxResult.error("该油企已存在切换支付渠道设置");
        }
        String stationNames = "";
        Set<String> stationNameSet = new HashSet<>();
        List<AutoPayWayInfo> autoPayWayInfoList = autoPayWayDto.getAutoPayWayInfos();
        for (AutoPayWayInfo autoPayWayInfo : autoPayWayInfoList) {
            Station station = stationMapper.selectStationById(autoPayWayInfo.getStationId());
            stationNameSet.add(station.getStationName());
        }

        for (String stationName : stationNameSet) {
            stationNames += stationName + ",";
        }

// 移除最后一个逗号
        if (stationNames.length() > 0) {
            stationNames = stationNames.substring(0, stationNames.length() - 1);
        }

        autoPayWayDto.setStationNames(stationNames);
// 获取当前时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(now);

// 设置createTime属性
        autoPayWayDto.setCreateTime(currentTime);
        long auto_pay_way_info_id = 0L;
        auto_pay_way_info_id = payWayMapper.insertAutoPayWay(autoPayWayDto);

        for (AutoPayWayInfo autoPayWayInfo : autoPayWayInfoList) {
            autoPayWayInfo.setAutoPayWayId(autoPayWayDto.getId());
            autoPayWayInfo.setEnterpriseId(autoPayWayDto.getEnterpriseId());
            autoPayWayInfo.setWayPayWay(autoPayWayDto.getWayPayWay());
            autoPayWayInfo.setCreateTime(currentTime);
            payWayMapper.insertAutoPayWayInfo(autoPayWayInfo);
        }
        if (auto_pay_way_info_id != 0L) {
            if(autoPayWayDto.getWayPayWay() == 0){
                selectAutoPayWay(0,0L,"0");
            }
            return AjaxResult.success("新增成功");
        } else {
            return AjaxResult.error("新增失败");
        }

    }


    @Override
    public int updateAutoPayWay(AutoPayWayDto autoPayWayDto) {
        if (autoPayWayDto.getId() == null) {
            throw new CustomException("id不能为空");
        }
        for (AutoPayWayInfo automaticClassInfo : autoPayWayDto.getAutoPayWayInfos()) {
            if (null == automaticClassInfo.getStationId()) {
                throw new CustomException("油站id不能为空");
            }
        }
        String stationNames = "";
        Set<String> stationNameSet = new HashSet<>();
        List<AutoPayWayInfo> autoPayWayInfoList = autoPayWayDto.getAutoPayWayInfos();
        for (AutoPayWayInfo autoPayWayInfo : autoPayWayInfoList) {
            Station station = stationMapper.selectStationById(autoPayWayInfo.getStationId());
            stationNameSet.add(station.getStationName());
        }

        for (String stationName : stationNameSet) {
            stationNames += stationName + ",";
        }

// 移除最后一个逗号
        if (stationNames.length() > 0) {
            stationNames = stationNames.substring(0, stationNames.length() - 1);
        }

        autoPayWayDto.setStationNames(stationNames);
// 获取当前时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(now);

// 设置createTime属性
        autoPayWayDto.setCreateTime(currentTime);
        long auto_pay_way_info_id = 0L;
        auto_pay_way_info_id = payWayMapper.updateAutoPayWay(autoPayWayDto);
        payWayMapper.deleteAutoPayWayInfo(autoPayWayDto.getId());
        for (AutoPayWayInfo autoPayWayInfo : autoPayWayInfoList) {
            autoPayWayInfo.setAutoPayWayId(autoPayWayDto.getId());
            autoPayWayInfo.setEnterpriseId(autoPayWayDto.getEnterpriseId());
            autoPayWayInfo.setWayPayWay(autoPayWayDto.getWayPayWay());
            autoPayWayInfo.setCreateTime(currentTime);
            payWayMapper.insertAutoPayWayInfo(autoPayWayInfo);
        }
        if (auto_pay_way_info_id != 0L) {
            return 1;
        } else {
            return 0;
        }
    }


    @Override
    public int deleteAutoPayWay(Long id) {
        if (id == null) {
            throw new CustomException("id不能为空");
        }
        AutoPayWayInfo autoPayWayInfo   =  payWayMapper.getOneAutoPayWayInfo(id);

        Station station = new Station();
        Long[] idList2 = payWayMapper.getAutoPayWayOver(autoPayWayInfo.getStationId());
        station.setPayWayIdList(idList2);
        station.setStationId(autoPayWayInfo.getStationId());
        stationController.autoPayWay(station);
        long auto_pay_way_info_id = 0L;
        auto_pay_way_info_id = payWayMapper.deleteAutoPayWayInfo(id);
        auto_pay_way_info_id = payWayMapper.deleteAutoPayWay(id);
        if (auto_pay_way_info_id != 0L) {
            return 1;
        } else {
            return 0;
        }
    }


    @Override
    public AjaxResult getSXFMnoServiceCharge(String mno) {
        try {

            String URL  =  tianqueURLVal + "/merchant/merchantInfoQuery";
            JSONObject reqData = new JSONObject();              //将业务参数存放在 JSON 对象中
            reqData.put("mno", mno);
            String req = this.getSXFPay(reqData);
            //此处不要改变reqData里面值的顺序用LinkedHashMap
            HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
            //组装加密串
            String signContent = RSASignature.getOrderContent(reqMap);
            //sign

            String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, tradeReversePayPrivatekey));
            reqMap.put("sign", sign);
            String reqStr = JSON.toJSONString(reqMap);

            log.info("sxfGoPay-随行付请求参数-" + reqStr);
            //调用第三方接口地址
            String resultJson = HttpUtils.connectPostUrl(URL, reqStr);

            log.info("sxfGoPay-随行付返回参数-" + resultJson);
// 解析resultJson
            JSONObject responseJson = JSONObject.parseObject(resultJson);
            return AjaxResult.success(responseJson);
        }   catch (Exception e){
        e.printStackTrace();
            return AjaxResult.error(e.toString());
    }

    }
    @Override
    public  void selectMnoAllRateList() {

        List<RateSettingDto> rateSettingList = payWayMapper.selectMnoAllRateList();
        for (RateSettingDto rateSetting:rateSettingList ){
            String mno =   rateSetting.getMno();
            BigDecimal wechatDebitScheduledRate =  rateSetting.getWechatDebitScheduledRate();
            payWayMapper.updatePayWayWxpos(wechatDebitScheduledRate,mno);
            BigDecimal alipayDebitScheduledRate =  rateSetting.getAlipayDebitScheduledRate();
            payWayMapper.updatePayWayZfb(alipayDebitScheduledRate,mno);
            BigDecimal bankCardDebitScheduledRate =  rateSetting.getBankCardDebitScheduledRate();
            payWayMapper.updatePayWayYhk(bankCardDebitScheduledRate,mno);
            payWayMapper.updateMnoAllRateList(mno);
        }

    }

    @Override
    public RateSettingDto selectMnoAllRate(String mno) {
        if (mno == null) {
            throw new CustomException("mno不能为空");
        }
        return payWayMapper.selectMnoAllRate(mno);

    }



    @Override
    public AjaxResult setMnoAllRate(RateSettingDto rateSettingDto) {
try{
    String URL  =  tianqueURLVal + "/merchant/merchantSetup";
    String yhkURL  =  tianqueURLVal + "/merchant/setCardRate";

    JSONObject reqData = new JSONObject();              //将业务参数存放在 JSON 对象中
    reqData.put("mno", rateSettingDto.getMno());
    JSONObject reqData2 = new JSONObject();              //将业务参数存放在 JSON 对象中
    reqData2.put("mno", rateSettingDto.getMno());
    List<Map<String, Object>> mapList  = new ArrayList<>();
    List<Map<String, Object>> mapListYhk  = new ArrayList<>();



    if (rateSettingDto.getStatus().equals("0")){
        Map<String, Object> objectMapwxj = new HashMap<>();
        Map<String, Object> objectMapzfbj = new HashMap<>();
        Map<String, Object> objectMapylminj = new HashMap<>();
        Map<String, Object> objectMapylmaxj = new HashMap<>();
        objectMapwxj.put("rateType","01");
        BigDecimal wxj  = rateSettingDto.getWechatDebitScheduledRate().divide(new BigDecimal("10"));
        objectMapwxj.put("rate",wxj);
        objectMapzfbj.put("rateType","02");
        BigDecimal zfbj  = rateSettingDto.getAlipayDebitScheduledRate().divide(new BigDecimal("10"));
        objectMapzfbj.put("rate",zfbj);
        objectMapylminj.put("rateType","06");
        BigDecimal ylminj  = rateSettingDto.getUnionPayDebitScheduledRate().divide(new BigDecimal("10"));
        objectMapylminj.put("rate",ylminj);
        objectMapylmaxj.put("rateType","07");
        BigDecimal ylmaxj  = rateSettingDto.getUnionPayDebitScheduledRateOver1000().divide(new BigDecimal("10"));
        objectMapylmaxj.put("rate",ylmaxj);
        mapList.add(objectMapwxj);
        mapList.add(objectMapzfbj);
            mapList.add(objectMapylminj);
            mapList.add(objectMapylmaxj);
    }else if(rateSettingDto.getStatus().equals("0")){

        return AjaxResult.error("暂不支持借贷分离设置");
    }else{
        return AjaxResult.error("是否借贷分离设置错误");
    }

    Map<String, Object> objectMapYhkJ = new HashMap<>();
    Map<String, Object> objectMapYhkD = new HashMap<>();
    Map<String, Object> objectMapYhkMax = new HashMap<>();
    objectMapYhkJ.put("type","21");
    BigDecimal yhkJ  = rateSettingDto.getBankCardCreditScheduledRate().divide(new BigDecimal("10"));
    objectMapYhkJ.put("rate",yhkJ);
    objectMapYhkD.put("type","22");
    BigDecimal yhkD  = rateSettingDto.getBankCardDebitScheduledRate().divide(new BigDecimal("10"));
    objectMapYhkD.put("rate",yhkD);
    objectMapYhkMax.put("type","23");
    BigDecimal yhkMax  = rateSettingDto.getDebitCardCap();
    objectMapYhkMax.put("rate",yhkMax);
    mapListYhk.add(objectMapYhkJ);
    mapListYhk.add(objectMapYhkD);
    mapListYhk.add(objectMapYhkMax);
    reqData2.put("bankCardRates",mapListYhk);




    reqData.put("qrcodeList",mapList);
    String req = this.getSXFPay(reqData);
    //此处不要改变reqData里面值的顺序用LinkedHashMap
    HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
    //组装加密串
    String signContent = RSASignature.getOrderContent(reqMap);
    //sign

    String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, tradeReversePayPrivatekey));
    reqMap.put("sign", sign);
    String reqStr = JSON.toJSONString(reqMap);

    log.info("sxfGoPay-随行付请求参数-" + reqStr);
    //调用第三方接口地址
    String resultJson = HttpUtils.connectPostUrl(URL, reqStr);

    log.info("sxfGoPay-随行付返回参数-" + resultJson);
// 解析resultJson
    JSONObject responseJson = JSONObject.parseObject(resultJson);
    String code = responseJson.getString("code");
    String msg = responseJson.getString("msg");
    if(code.equals("0000")){
        Map  respData =  responseJson.getJSONObject("respData");

        if( respData.get("bizCode").equals("0000")){

       }else{
        String bizMsg = respData.get("bizMsg").toString();
        return AjaxResult.error(bizMsg);
       }
    }else{
        return AjaxResult.error(msg);

    }
    String req2 = this.getSXFPay(reqData2);
    //此处不要改变reqData里面值的顺序用LinkedHashMap
    HashMap reqMap2 = JSON.parseObject(req2, LinkedHashMap.class, Feature.OrderedField);
    //组装加密串
    String signContent2 = RSASignature.getOrderContent(reqMap2);
    //sign

    String sign2 = RSASignature.encryptBASE64(RSASignature.sign(signContent2, tradeReversePayPrivatekey));
    reqMap2.put("sign", sign2);
    String reqStr2 = JSON.toJSONString(reqMap2);

    log.info("sxfGoPay-随行付请求参数-" + reqStr2);
    //调用第三方接口地址
    String resultJson2 = HttpUtils.connectPostUrl(yhkURL, reqStr2);

    log.info("sxfGoPay-随行付返回参数-" + resultJson2);
// 解析resultJson
    JSONObject responseJson2 = JSONObject.parseObject(resultJson2);
    String code2 = responseJson2.getString("code");
    String msg2 = responseJson2.getString("msg");
    if(code2.equals("0000")){
        Map  respData =  responseJson2.getJSONObject("respData");

        if( respData.get("bizCode").equals("0000")){


        }else{
            String bizMsg = respData.get("bizMsg").toString();
            return AjaxResult.error(bizMsg);
        }
    }else{
        return AjaxResult.error(msg2);

    }
    payWayMapper.deleteMnoAllRate(rateSettingDto.getMno());
    payWayMapper.setMnoAllRate(rateSettingDto);
    return AjaxResult.success();
    }   catch (Exception e){
        e.printStackTrace();
        return AjaxResult.error(e.toString());
    }
    }



    @Override
    public List<PayWay> getMnoByEnterpriseId(Long id) {
        if (id == null) {
            throw new CustomException("id不能为空");
        }
        return payWayMapper.getMnoByEnterpriseId(id);

    }

    @Override
    public List<AutoPayWayInfo> getAutoPayWayInfo(Long id) {
        if (id == null) {
            throw new CustomException("id不能为空");
        }
//        List<AutoPayWayInfo> i = new ArrayList<>();
        return payWayMapper.getAutoPayWayInfo(id);

    }

    @Override
    public void selectAutoPayWay(int wayPayWay, Long stationId, String oilGun) {

        if (wayPayWay == 0) {
            Map<String, Object> queryMap = new HashMap<String, Object>();
            queryMap.put("wayPayWay", wayPayWay);
            Set<Long> stationIds = payWayMapper.selectAutoPayWayStationId(queryMap);
            for (Long stationIdItem : stationIds) {
                queryMap.put("wayPayWay", wayPayWay);
                queryMap.put("stationId", stationIdItem);
                List<AutoPayWayInfo> autoPayWayInfos = payWayMapper.selectAutoPayWayInfo(queryMap);
                for (AutoPayWayInfo autoPayWayInfo : autoPayWayInfos) {
                    Long itemStationId = autoPayWayInfo.getStationId();
                    String payWayIdList = autoPayWayInfo.getPayWayIdList();
                    String weeks = autoPayWayInfo.getWeeks();
                    if (payWayIdList != null && !payWayIdList.isEmpty()) {
                        payWayIdList = payWayIdList.replaceAll("\\[|\\]", ""); // 去掉方括号
                        String[] idArray = payWayIdList.split(","); // 拆分成字符串数组
                        Long[] idList = new Long[idArray.length];
                        for (int i = 0; i < idArray.length; i++) {
                            String id = idArray[i].trim(); // 去掉空格
                            if (!id.isEmpty()) {
                                idList[i] = Long.parseLong(id); // 转换为 Long 类型并赋值给数组
                            }
                        }
                        boolean a = checkTimeInRange(autoPayWayInfo.getBeginTime(), autoPayWayInfo.getEndTime(), weeks);
                        if (a) {
                            Station station = new Station();
                            station.setPayWayIdList(idList);
                            station.setStationId(itemStationId);
                            stationController.autoPayWay(station);
                            break;
                        } else {
                            Station station = new Station();
                            Long[] idList2 = payWayMapper.getAutoPayWayOver(itemStationId);
                            station.setPayWayIdList(idList2);
                            station.setStationId(itemStationId);
                            stationController.autoPayWay(station);
                        }
                    } else {
                        System.out.println("payWayIdList is empty or null.");
                    }

                }

            }
        } else if (wayPayWay == 1) {
            Map<String, Object> queryMap = new HashMap<String, Object>();
            queryMap.put("wayPayWay", 1);


            Long stationIdItem = stationId;
            Map<String, Object> queryMap2 = new HashMap<String, Object>();
            queryMap2.put("wayPayWay", 1);
            queryMap2.put("stationId", stationId);
            AutoPayWayInfo autoRunPayWayInfo = payWayMapper.getRunCountAutoPayWayInfo(queryMap2);
            if (autoRunPayWayInfo != null) {
                Map<String, Object> queryMapCount = new HashMap<String, Object>();
                String lastDate = autoRunPayWayInfo.getLastData();
                queryMapCount.put("lastDate", lastDate);
                queryMapCount.put("stationId", stationId);
                Map<String, Object> countMap = payWayMapper.getOrderCount(queryMapCount);
                Long totalCount = (Long) countMap.get("count");
                int count = totalCount.intValue();
                if (count >= Integer.parseInt(autoRunPayWayInfo.getOrderCount())) {
                    AutoPayWayInfo changePayWayInfo = payWayMapper.getCountAutoPayWayInfo(queryMap2);
                    Long itemStationId = changePayWayInfo.getStationId();
                    String payWayIdList = changePayWayInfo.getPayWayIdList();
                    payWayIdList = payWayIdList.replaceAll("\\[|\\]", ""); // 去掉方括号
                    String[] idArray = payWayIdList.split(","); // 拆分成字符串数组
                    Long[] idList = new Long[idArray.length];
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim(); // 去掉空格
                        if (!id.isEmpty()) {
                            idList[i] = Long.parseLong(id); // 转换为 Long 类型并赋值给数组
                        }
                    }
                    Station station = new Station();
                    station.setPayWayIdList(idList);
                    station.setStationId(itemStationId);
                    stationController.autoPayWay(station);
                    changePayWayInfo.setNowRun("1");
                    changePayWayInfo.setRunCount(changePayWayInfo.getRunCount() + 1);
                    if(countMap.get("lastDate") != null){
                        String lastData = countMap.get("lastDate").toString();
                        changePayWayInfo.setLastData(lastData);
                    }else{
                        // 获取当前时间
                        LocalDateTime currentTime = LocalDateTime.now();
                        // 定义日期时间格式
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        // 将当前时间格式化为字符串
                        String currentTimeString = currentTime.format(formatter);
                        changePayWayInfo.setLastData(currentTimeString);
                    }
                    autoRunPayWayInfo.setNowRun("0");
                    payWayMapper.updateAutoPayWayInfo(autoRunPayWayInfo);
                    payWayMapper.updateAutoPayWayInfo(changePayWayInfo);
                }
            } else {
                AutoPayWayInfo changePayWayInfo = payWayMapper.getCountAutoPayWayInfo(queryMap2);
                if (changePayWayInfo != null) {
                    Long itemStationId = changePayWayInfo.getStationId();
                    String payWayIdList = changePayWayInfo.getPayWayIdList();
                    payWayIdList = payWayIdList.replaceAll("\\[|\\]", ""); // 去掉方括号
                    String[] idArray = payWayIdList.split(","); // 拆分成字符串数组
                    Long[] idList = new Long[idArray.length];
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim(); // 去掉空格
                        if (!id.isEmpty()) {
                            idList[i] = Long.parseLong(id); // 转换为 Long 类型并赋值给数组
                        }
                    }
                    Station station = new Station();
                    station.setPayWayIdList(idList);
                    station.setStationId(itemStationId);
                    stationController.autoPayWay(station);
                    changePayWayInfo.setNowRun("1");
                    changePayWayInfo.setRunCount(changePayWayInfo.getRunCount() + 1);
                    // 获取当前时间
                    LocalDateTime currentTime = LocalDateTime.now();
                    // 定义日期时间格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    // 将当前时间格式化为字符串
                    String currentTimeString = currentTime.format(formatter);
                    changePayWayInfo.setLastData(currentTimeString);
                    payWayMapper.updateAutoPayWayInfo(changePayWayInfo);
                }

            }

            Map<String, Object> queryMapByGun2 = new HashMap<String, Object>();
            queryMapByGun2.put("wayPayWay", 2);
            queryMapByGun2.put("stationId", stationIdItem);

            List<AutoPayWayInfo> autoCheckPayWayInfos = payWayMapper.selectAutoPayWayInfo(queryMapByGun2);
            if (autoCheckPayWayInfos != null && autoCheckPayWayInfos.size() > 0) {
                queryMapByGun2.put("oilGun", oilGun);
                List<AutoPayWayInfo> autoPayWayInfos = payWayMapper.selectAutoPayWayInfo(queryMapByGun2);
                if (autoPayWayInfos != null && autoPayWayInfos.size() > 0) {
                    AutoPayWayInfo runPayWayInfo = null;
                    for (AutoPayWayInfo autoPayWayInfo : autoPayWayInfos) {
                        if (runPayWayInfo==null){
                            String oilGunList = autoPayWayInfo.getOilGun();
                            String[] oilGunListArray = oilGunList.split(","); // 拆分成字符串数组
                            for (int n = 0; n < oilGunListArray.length; n++) {
                                String gun = oilGunListArray[n].trim(); // 去掉空格
                                if (!gun.isEmpty()) {
                                    if (gun.equals(oilGun)){
                                        runPayWayInfo = autoPayWayInfo;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (runPayWayInfo!=null){
                        String payWayIdList = runPayWayInfo.getPayWayIdList();
                        payWayIdList = payWayIdList.replaceAll("\\[|\\]", ""); // 去掉方括号
                        String[] idArray = payWayIdList.split(","); // 拆分成字符串数组
                        Long[] idList = new Long[idArray.length];
                        for (int i = 0; i < idArray.length; i++) {
                            String id = idArray[i].trim(); // 去掉空格
                            if (!id.isEmpty()) {
                                idList[i] = Long.parseLong(id); // 转换为 Long 类型并赋值给数组
                            }
                        }
                        Station station = new Station();
                        station.setPayWayIdList(idList);
                        station.setStationId(stationIdItem);
                        stationController.autoPayWay(station);
                    }else{
                        Station station = new Station();
                        Long[] idList2 = payWayMapper.getAutoPayWayOver(stationIdItem);
                        station.setPayWayIdList(idList2);
                        station.setStationId(stationIdItem);
                        stationController.autoPayWay(station);
                    }


                } else {
                    Station station = new Station();
                    Long[] idList2 = payWayMapper.getAutoPayWayOver(stationIdItem);
                    station.setPayWayIdList(idList2);
                    station.setStationId(stationIdItem);
                    stationController.autoPayWay(station);
                }
            }


        }
    }

    ;

    public static boolean checkTimeInRange(String startTime, String endTime, String weeks) {
        weeks = weeks.replaceAll("\\[|\\]", ""); // 去掉方括号
        String[] idArray = weeks.split(","); // 拆分成字符串数组
        List<Integer> daysOfWeek = new ArrayList<Integer>();
        for (int i = 0; i < idArray.length; i++) {
            String id = idArray[i].trim(); // 去掉空格
            if (!id.isEmpty()) {
                daysOfWeek.add(Integer.parseInt(id));
                ; // 转换为 Long 类型并赋值给数组
            }
        }
        // 获取当前时间和当前周的星期几
        LocalTime now = LocalTime.now();
        Integer currentDayOfWeek = LocalDate.now().getDayOfWeek().getValue();

        // 解析起始时间和结束时间
        LocalTime start = LocalTime.parse(startTime);
        LocalTime end = null;

if(endTime.equals("24:00")){
    String[] parts = endTime.split(":");
    int hour = Integer.parseInt(parts[0]);
    int minute = Integer.parseInt(parts[1]);
    int second = 0;

    if (hour == 24 && minute == 0 ) {
        hour = 23;
        minute = 59;
        second = 59;
    }

    String correctedTime = String.format("%02d:%02d:%02d", hour, minute, second);
    end = LocalTime.parse(correctedTime);
}else{
    end = LocalTime.parse(endTime);
}
        // 检查当前时间是否在指定的时间段内，并且当前周的星期几是否在指定的周内
        if (now.isAfter(start) && now.isBefore(end) && daysOfWeek.contains(currentDayOfWeek)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 批量删除支付配置信息
     *
     * @param payWayIds 需要删除的数据ID
     * @return 结果
     */
    public int deletePayWayByIds(Long[] payWayIds) {
        return payWayMapper.deletePayWayByIds(payWayIds);
    }

}
